package com.study.yygh.order.api;

import com.study.yygh.common.result.Result;
import com.study.yygh.order.service.PaymentService;
import com.study.yygh.order.service.WeixinService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author tao
 * @create 2021-11-26 17:44
 * @Description
 */

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private PaymentService paymentService;

    /**
     * 下单 生成二维码
     * @param orderId
     * @return
     */
    @GetMapping("/createNative/{orderId}")
    public Result createNative(
            @ApiParam(name = "orderId",value = "订单id",required = true)
            @PathVariable("orderId") String orderId){
        return Result.ok(weixinService.createNative(orderId));
    }

    /**
     * 查询支付状态
     * @param orderId 订单id
     * @return
     */
    @GetMapping("queryPaystatus/{orderId}")
    public Result queryPayStatus(@PathVariable("orderId") String orderId){
        // 调用微信接口实现支付状态查询
        Map<String, String> resultMap = weixinService.queryPayStatus(orderId);
        // 判断
        if(resultMap == null){
            return Result.fail().message("支付出错");
        }
        // 支付成功
        if("SUCCESS".equals(resultMap.get("trade_state"))){
            // 更新订单状态
            String out_trade_no = resultMap.get("out_trade_no");
            paymentService.paySuccess(out_trade_no,resultMap);
            return Result.ok().message("支付成功");
        }

        return Result.ok().message("支付中");
    }
}
